﻿using Microsoft.Web.WebView2.WinForms;
using System;
using System.Windows.Forms;

namespace LikeProxy.Controls
{
    public partial class BrowserControl : UserControl
    {
        private readonly WebView2 webView;
        public BrowserControl()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;
            webView = new WebView2
            {
                Dock = DockStyle.Fill
            };
            toolStripContainer.ContentPanel.Controls.Add(this.webView);
            webView.Source = new Uri("http://www.baidu.com");
        }
        public void ButtonClicked(object sender, EventArgs e)
        {
            ToolStripButton btn = sender as ToolStripButton;
            if (btn.Name == "btn_back")
            {
                webView.GoBack();
            }
            else if (btn.Name == "btn_forward")
            {
                webView.GoForward();
            }
            else if (btn.Name == "btn_do")
            {
                LoadUrl(text_address.Text);
            }
        }
        private void LoadUrl(string url)
        {
            if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
            {
                try
                {
                    
                    if (!url.StartsWith("http://"))
                    {
                        url = "http://" + url;
                    }
                    webView.CoreWebView2.Navigate(url);
                }
                catch (Exception)
                {

                }
                
            }
        }

        private void Text_address_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }
            LoadUrl(text_address.Text);
        }

    }
}
